using Microsoft.EntityFrameworkCore;
using GoodApi.Intefaces;
using Microsoft.AspNetCore.Mvc;
using GoodApi.Model;
using GoodApi.Common;
using GoodApi.Dto;
namespace GoodApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class GoodController : ControllerBase
{
    private readonly IRepository<Good> _goodRep;
    public GoodController(IRepository<Good> goodRep)
    {
        _goodRep = goodRep;
    }

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var obj = await _goodRep.GetAllAsync();
        if (obj.Count == 0)
        {
            return Ok(ApiResponse<string>.Fail(1004, "暂无商品"));
        }
        return Ok(ApiResponse<List<Good>>.Success(obj));
    }

    [HttpPost]
    public async Task<IActionResult> Add(GoodDto goodDto)
    {
        var obj = new Good { GoodName = goodDto.GoodName, Stock = goodDto.Stock };
        await _goodRep.AddAsync(obj);
        return Ok(ApiResponse<GoodDto>.Success(goodDto));
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Update(int id, GoodDto goodDto)
    {
        var obj = await _goodRep.GetByIdAsync(id);
        if (obj == null)
        {
            return Ok(ApiResponse<string>.Fail(1004, "查无商品,修改失败"));
        }
        obj.GoodName = goodDto.GoodName;
        obj.Stock = goodDto.Stock;
        await _goodRep.EditAsync(obj);
        return Ok(ApiResponse<GoodDto>.Success(goodDto));
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Del(int id)
    {
        var obj = await _goodRep.GetByIdAsync(id);
        if (obj == null)
        {
            return Ok(ApiResponse<string>.Fail(1004, "查无商品,删除失败"));
        }

        await _goodRep.DeleteAsync(obj);
        return Ok(ApiResponse<Good>.Success(obj));
    }

}